<?php
// app/controller/BusController.php
namespace app\api\controller;

use app\common\controller\Api;

class Lines extends Api
{
    /**
     * 根据站点名称获取所有经过线路的到站时间和发车时间
     */
    public function getLinesList()
    {
        $stationName=$this->request->request("station");
        
        if (!$stationName) {
            return json([
                'code' => 400,
                'msg' => '请输入站点名称',
                'data' => null
            ]);
        }
        
        // 1. 获取经过该站点的所有线路
        $stationLines = \app\admin\model\BusStation::where('station_name', $stationName)
                                 ->select();
        
        if ($stationLines->isEmpty()) {
            return json([
                'code' => 404,
                'msg' => '该站点暂无线路经过',
                'data' => null
            ]);
        }
        
        $result = [];
        
        // 2. 对每条线路计算到站时间和下一趟发车时间
        foreach ($stationLines as $station) {
            $lineId = $station['line_id'];
            
            // 获取线路信息
            $line = \app\admin\model\BusLine::find($lineId);
            if (!$line) {
                continue;
            }
            
            // 获取下一趟发车时间
            $nextDeparture = $this->getNextDepartureTime($lineId);
            
            // 获取到站时间
            $arrivalInfo = $this->getArrivalTime($lineId, $stationName);
            
            $result[] = [
                'line_info' => [
                    'line_id' => $line['id'],
                    'line_number' => $line['line_number'],
                    'line_name' => $line['line_name'],
                    'direction' => $line['direction'],
                    'start_station' => $line['start_station'],
                    'end_station' => $line['end_station'],
                    'station_order' => $station['station_order']
                ],
                'next_departure' => $nextDeparture,
                'arrival_info' => $arrivalInfo
            ];
        }
        
        return json([
            'code' => 200,
            'msg' => 'success',
            'data' => $result
        ]);
    }
    
    /**
     * 获取下一趟发车时间（优化班次逻辑）
     */
    private function getNextDepartureTime($lineId)
    {
        $currentTime = date('H:i:s');
        $currentWeekday = date('N'); // 1-7 周一到周日
        
        // 获取今天所有符合条件的班次
        $schedules = \app\admin\model\BusSchedule::where('line_id', $lineId)
                              ->where(function($query) use ($currentWeekday) {
                                  // 周一到周五的班次 (1-5)
                                  if ($currentWeekday >= 1 && $currentWeekday <= 5) {
                                      $query->whereOr('weekdays', '1-5');
                                  }
                                  // 周一到周六的班次 (1-6)
                                  if ($currentWeekday >= 1 && $currentWeekday <= 6) {
                                      $query->whereOr('weekdays', '1-6');
                                  }
                                  // 每天的班次 (1-7)
                                  $query->whereOr('weekdays', '1-7');
                                  // 特定周几的班次
                                  $query->whereOr('weekdays', 'like', '%' . $currentWeekday . '%');
                              })
                              ->where('departure_time', '>', $currentTime)
                              ->order('departure_time', 'asc')
                              ->select();
        
        if (!$schedules->isEmpty()) {
            $nextSchedule = $schedules[0];
            return [
                'departure_time' => $nextSchedule['departure_time'],
                'remaining_minutes' => $this->calculateTimeDiff($currentTime, $nextSchedule['departure_time']),
                'weekdays' => $nextSchedule['weekdays'],
                'schedule_type' => $nextSchedule['schedule_type']
            ];
        }
        
        // 如果今天没有后续班次，返回明天第一班
        $tomorrowWeekday = $currentWeekday == 7 ? 1 : $currentWeekday + 1;
        $tomorrowSchedules = \app\admin\model\BusSchedule::where('line_id', $lineId)
                                       ->where(function($query) use ($tomorrowWeekday) {
                                           // 周一到周五的班次 (1-5)
                                           if ($tomorrowWeekday >= 1 && $tomorrowWeekday <= 5) {
                                               $query->whereOr('weekdays', '1-5');
                                           }
                                           // 周一到周六的班次 (1-6)
                                           if ($tomorrowWeekday >= 1 && $tomorrowWeekday <= 6) {
                                               $query->whereOr('weekdays', '1-6');
                                           }
                                           // 每天的班次 (1-7)
                                           $query->whereOr('weekdays', '1-7');
                                           // 特定周几的班次
                                           $query->whereOr('weekdays', 'like', '%' . $tomorrowWeekday . '%');
                                       })
                                       ->order('departure_time', 'asc')
                                       ->select();
        
        if (!$tomorrowSchedules->isEmpty()) {
            $firstSchedule = $tomorrowSchedules[0];
            return [
                'departure_time' => $firstSchedule['departure_time'],
                'remaining_minutes' => '明日首班',
                'is_tomorrow' => true,
                'weekdays' => $firstSchedule['weekdays'],
                'schedule_type' => $firstSchedule['schedule_type']
            ];
        }
        
        return null;
    }
    
    /**
     * 获取到站时间（基于预设时间计算）
     */
    private function getArrivalTime($lineId, $stationName)
    {
        // 获取站点信息
        $station = \app\admin\model\BusStation::where('line_id', $lineId)
                           ->where('station_name', $stationName)
                           ->find();
        
        if (!$station) {
            return null;
        }
        
        $currentTime = date('H:i:s');
        $currentWeekday = date('N');
        
        // 查找最近已发车的班次
        $latestSchedules = \app\admin\model\BusSchedule::where('line_id', $lineId)
                                     ->where(function($query) use ($currentWeekday) {
                                         // 周一到周五的班次 (1-5)
                                         if ($currentWeekday >= 1 && $currentWeekday <= 5) {
                                             $query->whereOr('weekdays', '1-5');
                                         }
                                         // 周一到周六的班次 (1-6)
                                         if ($currentWeekday >= 1 && $currentWeekday <= 6) {
                                             $query->whereOr('weekdays', '1-6');
                                         }
                                         // 每天的班次 (1-7)
                                         $query->whereOr('weekdays', '1-7');
                                         // 特定周几的班次
                                         $query->whereOr('weekdays', 'like', '%' . $currentWeekday . '%');
                                     })
                                     ->where('departure_time', '<=', $currentTime)
                                     ->order('departure_time', 'desc')
                                     ->select();
        
        if (!$latestSchedules->isEmpty()) {
            $latestSchedule = $latestSchedules[0];
            
            // 计算预计到达时间
            $departureTimestamp = strtotime(date('Y-m-d') . ' ' . $latestSchedule['departure_time']);
            $estimatedArrivalTimestamp = $departureTimestamp + ($station['estimated_minutes'] * 60);
            $currentTimestamp = time();
            
            $remainingSeconds = $estimatedArrivalTimestamp - $currentTimestamp;
            
            // 如果车辆已经过站，返回0
            if ($remainingSeconds < 0) {
                $remainingSeconds = 0;
            }
            
            return [
                'data_source' => 'preset',
                'estimated_arrival_seconds' => $remainingSeconds,
                'estimated_arrival_minutes' => ceil($remainingSeconds / 60),
                'departure_time' => $latestSchedule['departure_time'],
                'station_order' => $station['station_order'],
                'schedule_type' => $latestSchedule['schedule_type']
            ];
        }
        
        return null;
    }
    
    /**
     * 计算时间差（分钟）
     */
    private function calculateTimeDiff($startTime, $endTime)
    {
        $start = strtotime($startTime);
        $end = strtotime($endTime);
        $diff = round(($end - $start) / 60);
        return $diff > 0 ? $diff : 0;
    }
    
    /**
     * 获取线路详细信息（备用接口）
     */
    public function getLineInfo()
    {
        $lineNumber = $this->request->param('line_number');
        $direction = $this->request->param('direction', 0);
        
        if (!$lineNumber) {
            return json([
                'code' => 400,
                'msg' => '请输入线路编号',
                'data' => null
            ]);
        }
        
        $line = \app\admin\model\BusLine::where('line_number', $lineNumber)
                      ->where('direction', $direction)
                      ->find();
        
        if (!$line) {
            return json([
                'code' => 404,
                'msg' => '线路不存在',
                'data' => null
            ]);
        }
        
        // 获取线路的所有站点
        $stations = \app\admin\model\BusStation::where('line_id', $line['id'])
                             ->order('station_order', 'asc')
                             ->select();
        
        // 获取发车时刻表
        $schedules = \app\admin\model\BusSchedule::where('line_id', $line['id'])
                               ->order('departure_time', 'asc')
                               ->select();
        
        return json([
            'code' => 200,
            'msg' => 'success',
            'data' => [
                'line_info' => $line,
                'stations' => $stations,
                'schedules' => $schedules
            ]
        ]);
    }
}